package com.rookie.shiro.module.util;


import com.rookie.shiro.module.constant.ErrorEnum;
import com.rookie.shiro.module.constant.SecurityConstant;
import com.rookie.shiro.module.constant.TokenTypeEnum;
import com.rookie.shiro.module.entity.LoginVO;
import com.rookie.shiro.module.exception.CommonException;
import org.apache.shiro.SecurityUtils;

import java.util.Map;

/**
 * @author rookie
 */
public class TokenUtils {

    /**
     * 获取token
     *
     * @return token
     */
    public static String getToken() {
        return (String) SecurityUtils.getSubject().getPrincipal();
    }


    public static Integer getUserRoleId() {
        Map userInfo = getUserInfo(null);
        return (Integer) userInfo.get("roleId");
    }

    public static Integer getUserId() {
        Map userInfo = getUserInfo(null);
        return (Integer) userInfo.get("id");
    }

    public static String getUserName() {
        Map userInfo = getUserInfo(null);
        return (String) userInfo.get("userName");
    }

    public static String getUserName(String token) {
        Map userInfo = getUserInfo(token);
        return (String) userInfo.get("userName");
    }

    private static Map getUserInfo(String token){
        if (token == null){
            token = getToken();
        }
        Class<?> tokenType = getTokenType(token);
        String userInfo = JwtUtils.getClaim(token, SecurityConstant.TOKEN_USER_INFO_NAME);
        Map userInfoMap = JsonUtils.getBean(userInfo, Map.class);
        if (userInfoMap == null){
            throw new CommonException(ErrorEnum.E_30004.getErrorMsg());
        }
        return userInfoMap;
    }


    private static Class<?> getTokenType(String token) {
        String type = JwtUtils.getClaim(token, SecurityConstant.TOKEN_TYPE_NAME);
        TokenTypeEnum typeEnum = TokenTypeEnum.getCode(type);
        if (typeEnum == null) {
            throw new CommonException(ErrorEnum.E_30004.getErrorMsg());
        }

        switch (typeEnum) {
            case ADMIN:
                return LoginVO.class;
            default:
                throw new CommonException(ErrorEnum.E_30004.getErrorMsg());
        }
    }
}
